<template>
  <div class="copy-campaign">
    <div class="root">
      <el-drawer
        :visible.sync="dialogVisible"
        :modal="false"
        size="calc(100vw - 220px)"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        :with-header="false">
        <cs-drawer-container>
          <div class="edit-ad-group-box">
            <div class="edit-ad-group-box-new">
              <el-card>
                <span slot="header">复制广告</span>
                <el-form ref="form" :model="campaignForm" label-width="120px" :rules="rules">
                  <el-form-item label="广告账户" prop="platformId">
                    <el-select style="width: 100%" size="mini" v-model="campaignForm.platformId" placeholder="请选择活动账户"
                               @change="handleChangePlatform" v-loading="platformLoading">
                      <el-option
                        v-for="item in accountList"
                        :key="item.id"
                        :value="item.platformId"
                        :label="item.name+'ID:'+item.platformId"
                        :disabled="options.campaignAppProfilePageState === 'ON'&& item.platformId !== options.platformId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-radio-group v-model="campaignForm.createType" @change="handleChangeCreateType">
                      <el-radio :label="1">到现有推广系列</el-radio>
                      <el-radio :label="2">到新的推广系列</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item prop="campaignId" v-if="campaignForm.createType === 1">
                    <el-select v-model="campaignForm.campaignId"
                               style="width: 100%"
                               placeholder="请选择" size="mini"
                               filterable
                               @change="handleChangeCampaign" :disabled="campaignListLoading"
                               v-loading="campaignListLoading">
                      <el-option v-for="item in campaignList" :key="item.id" :label="item.campaignName"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="推广系列名称" prop="campaignName" v-else>
                    <el-input size="mini" v-model="campaignForm.campaignName"></el-input>
                  </el-form-item>
                  <el-form-item v-if="campaignForm.createType === 1">
                    <el-radio-group v-model="campaignForm.createAdgroup" @change="handleChangeCreateAdgroup">
                      <el-radio :label="1">到现有广告组</el-radio>
                      <el-radio :label="2">到新的广告组</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="campaignForm.createAdgroup === 1&& campaignForm.createType === 1">
                    <el-select v-model="campaignForm.adGroupId" filterable style="width: 100%"
                               placeholder="请选择" size="mini" @change="handleChangeAdGroup">
                      <el-option v-for="item in adGroupList" :key="item.id" :label="item.adgroupName"
                                 :value="item.id" :disabled="item.creativeMaterialMode==='DYNAMIC'">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="复制数量">
                    <el-input-number size="mini" v-model="campaignForm.num" :disabled="true"></el-input-number>
                  </el-form-item>
                  <el-form-item label="APP">
                    <el-image :src="options.os === 1 ? androidImage: iosImage"
                              style="height: 25px;width: 25px;vertical-align: middle"></el-image>&nbsp;{{
                      options.appName
                    }}
                    <el-checkbox v-model="campaignForm.ios14Camppaign"
                                 style="margin-left: 30px"
                                 disabled @change="handleChangeIos14Switch">iOS 14
                    </el-checkbox>
                    <el-checkbox v-model="campaignForm.campaignAppProfilePageState "
                                 style="margin-left: 30px"
                                 true-label="ON"
                                 false-label="OFF"
                                 disabled>APPO
                    </el-checkbox>
                  </el-form-item>
                  <el-form-item label="预算" prop="budget">
                    <el-input
                      size="mini"
                      v-model="campaignForm.budget" class="input-with-select" :disabled="campaignForm.createType === 1"
                      placeholder="50.00以上"
                      oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                      <el-select style="width: 100px" id="AdGroupBudgetChange" v-model="campaignForm.budgetMode"
                                 slot="prepend" placeholder="预算模式"
                                 :disabled="campaignForm.createType === 1">
                        <el-option v-for="item in budgetModeList" :key="item.value" :label="item.label"
                                   :value="item.value"></el-option>
                      </el-select>
                      <template slot="append">USD</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="推广目标">
                    应用推广
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            <div class="edit-ad-group-box-left">
              <el-card v-loading="campaignForm.createAdgroup === 1&&campaignForm.createType === 1"
                       element-loading-background="rgba(0, 0, 0, 0.2)" element-loading-spinner="none">
                <span slot="header">广告组</span>
                <ad-group-form ref="adGroupForm" :options="adGroupOptions"
                               :current-account-id="campaignForm.platformId"></ad-group-form>
              </el-card>
            </div>
            <div class="edit-ad-group-box-right">
              <el-card v-for="(item, index) in ttAdList" style="margin-bottom: 10px" :key="index">
                <div slot="header" class="clearfix">
                  <span>{{item.isEdit}}</span>
                  <el-button style="float: right; padding: 3px 0;color: #F56C6C; margin-left: 10px" type="text"
                             @click="delAd(index)">删除
                  </el-button>
                  <el-button style="float: right; padding: 3px 0" type="text" @click="editAd(item)">修改</el-button>
                </div>
                <video
                  v-if="item.creativeType == 1"
                  style="width: 100px; height: 100px"
                  :src="item.creativeUrl"
                >
                </video>
                <el-image
                  v-else
                  style="width: 100px; height: 100px"
                  :src="item.creativeUrl"
                  :fit="'cover'"
                >
                </el-image>
                <el-descriptions :column="1">
                  <el-descriptions-item label="广告名">{{ item.adName }}</el-descriptions-item>
                  <el-descriptions-item label="广告ID">{{ item.ttAdId }}</el-descriptions-item>
                </el-descriptions>
              </el-card>
            </div>
          </div>
          <template v-slot:bottom>
            <el-button slot="bottom" size="mini" @click="dialogVisible = false">取消</el-button>
            <el-button slot="bottom" size="mini" type="primary" @click="submitForm">发布并暂停</el-button>
          </template>
        </cs-drawer-container>
        <el-drawer
          :visible="editAdDrawer"
          :append-to-body="true"
          :modal="false"
          :close-on-click-modal="false"
          :with-header="false"
          size="46%"
          class="append-to-body"
        >
          <cs-drawer-container>
            <div class="creative-drawer-box">
              <ad-form v-if="editAdDrawer" ref="adForm" :options="adOptions"
                       :platform-app-id="options.appId" :ad-group="adGroupOptions"
                       :is-origin-account="isOriginAccount" :campaign="options"
                       :current-account-id="options.platformId"></ad-form>
            </div>
            <template v-slot:bottom>
              <el-button slot="bottom" size="mini" @click="editAdDrawer = false">取消</el-button>
              <el-button slot="bottom" size="mini" type="primary" @click="handleSaveAd">保存</el-button>
            </template>
          </cs-drawer-container>
        </el-drawer>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import AdGroupForm from "@/views/campaign-management/components/AdGroupFormB";
import {
  confirmCopyCampaign,
  createAdCampaign,
  createBatchAd,
  createBatchAdGroup,
  getAdGroupList,
  getCampaignList,
  getCopyAdgroupDetail,
  getIos14Quota,
} from "@/api/campaign-management/campaign-management";
import {getActiveAccountList} from "@/api/campaign/campaign";
import AdForm from "@/views/campaign-management/components/AdFormB";

export default {
  name: "AdClone",
  components: {
    CsDrawerContainer,
    AdGroupForm,
    AdForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object
    },
    offerId: {
      type: String
    },
    copyAdList: {
      type: Array
    }
  },
  created() {
    this.getActiveAccountList()
    this.getCampaignList()
    this.ttAdList = this.copyAdList.map(item => {
      item.isEdit = '待修改'
      return item
    })
    this.adGroupOptions.appId = this.options.appId
    this.campaignForm.campaignAppProfilePageState = this.options.campaignAppProfilePageState
    this.campaignForm.ios14Camppaign = this.options.campaignType === 'IOS14_CAMPAIGN'
  },
  data() {
    var checkCampaignName = (rule, value, callback) => {
      if (this.campaignForm.createType === 2) {
        if (value === '') {
          callback(new Error('请输入推广系列名称'));
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    var checkCampaignId = (rule, value, callback) => {
      if (this.campaignForm.createType === 1) {
        if (value === '') {
          callback(new Error('请选择推广系列'));
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    var validateCampaignBudget = (rule, value, callback) => {
      if (this.campaignForm.budgetMode !== 'BUDGET_MODE_INFINITE') {
        if (value === '') {
          callback(new Error('请输入预算'))
        } else if (parseInt(value) < 50 || parseInt(value) > 10000000) {
          callback(new Error('预算应为 50.00 - 10,000,000.00间的纯数字'))
        } else if (this.campaignForm.budgetMode === '') {
          callback(new Error('请选择预算模式'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      campaignForm: {
        campaignId: '',
        campaignName: '',
        num: 1,
        platformId: '',
        budget: '',
        createType: 1,
        budgetMode: '',
        ios14Camppaign: false,
        createAdgroup: 1,
        adGroupId: '',
        campaignAppProfilePageState: 'OFF',
        timezoneOffset: 0
      },
      adGroupTableData: [],
      editAdGroupDrawer: true,
      accountList: [],
      rules: {
        platformId: [
          {required: true, message: '请选择账户', trigger: 'change'}
        ],
        campaignName: [
          {validator: checkCampaignName, trigger: 'blur'},
        ],
        campaignId: [
          {validator: checkCampaignId, trigger: 'change'}
        ],
        budget: [{validator: validateCampaignBudget, trigger: 'blur'}]
      },
      adForm: {},
      editAdDrawer: false,
      adOptions: null,
      submitCampaignLoading: false,
      budgetModeList: [{
        label: '日预算',
        value: 'BUDGET_MODE_DAY'
      }, {
        label: '总预算',
        value: 'BUDGET_MODE_TOTAL'
      },
        {
          label: '不限预算',
          value: 'BUDGET_MODE_INFINITE'
        }],
      isOriginAccount: false,
      levelQuota: {},
      campaignList: [],
      platformLoading: false,
      campaignListLoading: false,
      androidImage: '',
      iosImage: '',
      adGroupList: [],
      ttAdList: [],
      adLength: 0
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val || false)
      }
    },
    adGroupOptions() {
      return {
        appId: this.options.appId,
        platformId: this.campaignForm.platformId,
        timezoneOffset: this.campaignForm.timezoneOffset,
        os: this.options.os,
      }
    }
  },
  methods: {
    async getActiveAccountList() {
      this.platformLoading = true
      const {data: res} = await getActiveAccountList(this.offerId).finally(() => {
        this.platformLoading = false
      })
      this.accountList = res.data
    },
    confirmCopyCampaign() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.options.campaignAppProfilePageState === 'ON') {
          if (!this.isOriginAccount) return this.$message.error('APPO广告只允许复制到当前账户')
          await this.getLevelQuota()
          if (this.levelQuota.campaignQuota.availableQuota === 0) return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
        }
        const {data: res} = await confirmCopyCampaign({
          campaignId: this.campaignForm.campaignId,
          newCampaignName: this.campaignForm.campaignName,
          platformId: this.campaignForm.platformId
        })
        this.adGroupTableData = res.data.map(item => {
          item.isEdit = '待修改'
          if (!this.isOriginAccount) {
            item.ttAdList.forEach(ad => {
              ad.identityId = ad.adIdentityName
              ad.pageId = ''
              ad.landingPageUrl = ''
            })
          }
          return item
        })
      })
    },
    editAdGroup(row) {
      this.adGroupOptions = row
      this.editAdGroupDrawer = true
    },
    editAd(row) {
      this.adOptions = row
      this.editAdDrawer = true
    },
    handleSaveAd() {
      this.$refs.adForm.$refs.adForm.validate(valid => {
        if (!valid) return
        if (this.adOptions.creativeMaterialMode === 'DYNAMIC') {
          if (this.$refs.adForm.adForm.callToActionType == '0' && this.$refs.adForm.acoCTAs.length === 0) return this.$message.error('CTA不能为空')
          const ttAdList = []
          let step = 1
          this.$refs.adForm.acoCreatives.forEach(creative => {
            this.$refs.adForm.acoAdTexts.forEach(text => {
              if (this.$refs.adForm.adForm.callToActionType === '1') {
                ttAdList.push(
                  {
                    "adName": creative.name + "-" + (step++),
                    "identityId": this.$refs.adForm.adForm.identityId,
                    "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                    "adFormat": this.$refs.adForm.adForm.adFormat,
                    "callToActionType": this.$refs.adForm.adForm.callToActionType,
                    "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                    "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                    "creativeList": this.$refs.adForm.adForm.creativeList,
                    "adText": text,
                    "callToAction": '',
                    "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                    "creativeId": creative.id,
                    "creativeType": creative.type,
                    "platformId": this.$refs.adForm.adForm.platformId,
                    "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                    "imageUrl": this.$refs.adForm.adForm.imageUrl,
                    "pageId": this.$refs.adForm.adForm.pageId,
                    "creativeUrl": creative.creativeUrl,
                  }
                )
              } else {
                this.$refs.adForm.acoCTAs.forEach(cta => {
                  ttAdList.push(
                    {
                      "adName": creative.name + "-" + (step++),
                      "identityId": this.$refs.adForm.adForm.identityId,
                      "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                      "adFormat": this.$refs.adForm.adForm.adFormat,
                      "callToActionType": this.$refs.adForm.adForm.callToActionType,
                      "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                      "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                      "creativeList": this.$refs.adForm.adForm.creativeList,
                      "adText": text,
                      "callToAction": cta,
                      "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                      "creativeId": creative.id,
                      "creativeType": creative.type,
                      "platformId": this.$refs.adForm.adForm.platformId,
                      "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                      "imageUrl": this.$refs.adForm.adForm.imageUrl,
                      "pageId": this.$refs.adForm.adForm.pageId,
                      "creativeUrl": creative.creativeUrl
                    }
                  )
                })
              }
            })
          })
          this.ttAdList = ttAdList
          this.adGroupOptions.acoCreatives = this.$refs.adForm.acoCreatives
          this.adGroupOptions.acoCTAs = this.$refs.adForm.acoCTAs
          this.adGroupOptions.acoAdTexts = this.$refs.adForm.acoAdTexts
        } else {
          this.adOptions.adName = this.$refs.adForm.adForm.adName
          this.adOptions.identityId = this.$refs.adForm.adForm.identityId
          this.adOptions.autoCreateType = this.$refs.adForm.adForm.autoCreateType
          this.adOptions.adFormat = this.$refs.adForm.adForm.adFormat
          this.adOptions.callToActionType = this.$refs.adForm.adForm.callToActionType
          this.adOptions.impressionTrackingUrl = this.$refs.adForm.adForm.impressionTrackingUrl
          this.adOptions.clickTrackingUrl = this.$refs.adForm.adForm.clickTrackingUrl
          this.adOptions.creativeList = this.$refs.adForm.adForm.creativeList
          this.adOptions.adText = this.$refs.adForm.adForm.adText
          this.adOptions.callToAction = this.$refs.adForm.adForm.callToAction
          this.adOptions.adIdentityName = this.$refs.adForm.adForm.adIdentityName
          this.adOptions.creativeId = this.$refs.adForm.adForm.creativeId
          this.adOptions.platformId = this.$refs.adForm.adForm.platformId
          this.adOptions.landingPageUrl = this.$refs.adForm.adForm.landingPageUrl
          this.adOptions.pageId = this.$refs.adForm.adForm.pageId
          this.adOptions.creativeType = this.$refs.adForm.adForm.creativeType
          this.adOptions.creativeUrl = this.$refs.adForm.adForm.creativeUrl
          this.adOptions.imageUrl =  this.$refs.adForm.adForm.imageUrl
        }
        this.adGroupOptions.isEditAd = true
        this.adOptions.isEdit = '已保存'
        this.editAdDrawer = false
      })

    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.submitCampaignLoading) return
        const ttAdList = this.ttAdList.map(ad => {
          return {
            "adName": ad.adName,
            "adText": ad.adText,
            "adFormat": ad.adFormat,
            "callToActionType": ad.callToActionType,
            "callToAction": ad.callToAction,
            "clickTrackingUrl": ad.clickTrackingUrl,
            "creativeId": ad.creativeId,
            "impressionTrackingUrl": ad.impressionTrackingUrl,
            "operationStatus": "DISABLE",
            "identityType": "CUSTOMIZED_USER",
            "identityId": ad.identityId,
            "adIdentityName": ad.adIdentityName,
            "proportion": ad.proportion,
            "creativeType": ad.creativeType,
            "landingPageUrl": ad.landingPageUrl,
            "pageId": ad.pageId,
            "imageUrl": ad.imageUrl
          }
        })
        const actionScene = []
        if (this.$refs.adGroupForm.adGroupForm.videoUserActions.VIDEO_RELATED.length) {
          actionScene.push('VIDEO_RELATED')
        }
        if (this.$refs.adGroupForm.adGroupForm.videoUserActions.CREATOR_RELATED.length) {
          actionScene.push('CREATOR_RELATED')
        }
        const adGroups = []
        adGroups.push({
          "adgroupName": this.$refs.adGroupForm.adGroupForm.adgroupName,
          "age": this.$refs.adGroupForm.adGroupForm.age.join(','),
          "gender": this.$refs.adGroupForm.adGroupForm.gender,
          "languages": this.$refs.adGroupForm.adGroupForm.languages.join(','),
          "locationIds": this.$refs.adGroupForm.adGroupForm.locationIds.join(','),
          "autoTargetingEnabled": this.$refs.adGroupForm.adGroupForm.autoTargetingEnabled,
          "bidType": this.$refs.adGroupForm.adGroupForm.bidType,
          "budget": this.$refs.adGroupForm.adGroupForm.budget,
          "budgetMode": this.$refs.adGroupForm.adGroupForm.budgetMode,
          "commentDisabled": this.$refs.adGroupForm.adGroupForm.commentDisabled,
          "householdIncome": this.$refs.adGroupForm.adGroupForm.householdIncome.join(','),
          "optimizationEvent": this.$refs.adGroupForm.adGroupForm.optimizationEvent,
          "optimizationGoal": this.$refs.adGroupForm.adGroupForm.optimizationGoal,
          "pacing": this.$refs.adGroupForm.adGroupForm.pacing,
          "placementType": this.$refs.adGroupForm.adGroupForm.placementType,
          "scheduleStartTime": this.$refs.adGroupForm.adGroupForm.scheduleStartTime,
          "scheduleEndTime": this.$refs.adGroupForm.adGroupForm.scheduleEndTime,
          "scheduleType": this.$refs.adGroupForm.adGroupForm.scheduleType,
          "videoDownloadDisabled": this.$refs.adGroupForm.adGroupForm.videoDownloadDisabled,
          "blockedPangleDisabled": this.$refs.adGroupForm.adGroupForm.blockedPangleDisabled,
          "placement": this.$refs.adGroupForm.adGroupForm.placement.join(','),
          "interestCategoryIds": this.$refs.adGroupForm.adGroupForm.interestCategoryIds.join(','),
          "interestCategory": JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestCategory),
          "operationStatus": "DISABLE",
          "platformId": this.$refs.adGroupForm.adGroupForm.platformId,
          "billingEvent": this.$refs.adGroupForm.adGroupForm.optimizationGoal === "CLICK" ? 'CPC' : 'OCPM',
          "dailyRetentionRatio": this.$refs.adGroupForm.adGroupForm.dailyRetentionRatio,
          "deepBidType": this.$refs.adGroupForm.adGroupForm.deepBidType,
          "roasBid": this.$refs.adGroupForm.adGroupForm.roasBid,
          "audienceIds": this.$refs.adGroupForm.adGroupForm.audienceIds.join(','),
          "excludedAudienceIds": this.$refs.adGroupForm.adGroupForm.excludedAudienceIds.join(','),
          "expansionEnabled": this.$refs.adGroupForm.adGroupForm.expansionTypes.length > 0 ? 1 : 0,
          "expansionTypes": this.$refs.adGroupForm.adGroupForm.expansionTypes.join(','),
          "videoUserActions": JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoUserActions),
          "actionPeriod": this.$refs.adGroupForm.adGroupForm.actionPeriod,
          "creatorRelatedCategoryIds": this.$refs.adGroupForm.adGroupForm.creatorRelatedCategoryIds.join(','),
          "creatorRelatedCategory": JSON.stringify(this.$refs.adGroupForm.adGroupForm.creatorRelatedCategory),
          "videoRelatedCategoryIds": this.$refs.adGroupForm.adGroupForm.videoRelatedCategoryIds.join(','),
          "videoRelatedCategory": JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoRelatedCategory),
          "creativeMaterialMode": this.$refs.adGroupForm.adGroupForm.creativeMaterialMode,
          "interestsByKeyword": JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestsByKeyword),
          "interestsByKeywordIds": this.$refs.adGroupForm.adGroupForm.interestsByKeywordIds.join(','),
          "bidPrice": this.$refs.adGroupForm.adGroupForm.bidPrice,
          "conversionBidPrice": this.$refs.adGroupForm.adGroupForm.conversionBidPrice,
          "actionScene": actionScene.join(','),
          "appId": this.options.appId,
          "os": this.options.os,
          "shareDisabled": this.$refs.adGroupForm.adGroupForm.shareDisabled,
          ttAdList
        })
        const campaign = {
          "budget": this.campaignForm.budget,
          "budgetMode": this.campaignForm.budgetMode,
          "budgetOptimizeSwitch": 0,
          "campaignName": this.campaignForm.campaignName,
          "campaignType": this.campaignForm.ios14Camppaign ? 'IOS14_CAMPAIGN' : 'REGULAR_CAMPAIGN',
          "objectiveType": 'APP_INSTALL',
          "operationStatus": "DISABLE",
          "platformId": this.campaignForm.platformId,
          "offerId": this.offerId,
          "appName": this.options.appName,
          "appId": this.options.appId,
          "os": this.options.os,
        }
        // debugger
        if (this.campaignForm.createType === 1) { // 现有广系列
          console.log('现有推广系列')
          if (this.campaignForm.createAdgroup === 1) {
            console.log('现有广告组')
            await this.getAdsByAdGroup()
            if ((this.adLength + this.ttAdList.length) > 20) return this.$message.error('超出创建广告上限')
            this.submitCampaignLoading = true
            await createBatchAd(this.campaignForm.adGroupId,
              ttAdList).finally(() => {
              this.submitCampaignLoading = false
            })
            this.$message.success('复制成功')
            this.dialogVisible = false
          } else {
            console.log('新的广告组')
            await this.$refs.adGroupForm.$refs.adGroupForm.validate(async valida => {
                if (!valida) return
                this.submitCampaignLoading = true
                await createBatchAdGroup(this.campaignForm.campaignId,
                  adGroups
                ).finally(() => {
                  this.submitCampaignLoading = false
                })
                this.$message.success('复制成功')
                this.dialogVisible = false
              }
            )
          }
        } else {
          console.log('新的推广系列')
          await this.$refs.adGroupForm.$refs.adGroupForm.validate(async valida => {
            if (!valida) return
            this.submitCampaignLoading = true
            await createAdCampaign({
              campaign,
              adGroups,
            }).finally(() => {
              this.submitCampaignLoading = false
            })
            this.$message.success('复制成功')
            this.dialogVisible = false
          })
        }
      })

    },
    delAdGroup(index) {
      this.adGroupTableData.splice(index, 1)
    },
    delAd(index) {
      this.ttAdList.splice(index, 1)
    },
    handleChangePlatform(val) {
      this.isOriginAccount = this.options.platformId === val
      const platform = this.accountList.find(item => item.platformId === val)
      this.campaignForm.timezoneOffset = platform.timezoneOffset
      // console.log(this.accountList)
    },
    async getLevelQuota() {
      const {data: res} = await getIos14Quota({
        appId: this.options.appId,
        platformId: this.campaignForm.platformId
      })
      this.levelQuota = res.data
    },
    // 获取所有的campaign列表
    async getCampaignList() {
      this.campaignListLoading = true
      const {data: res} = await getCampaignList({
        offerId: this.offerId,
        campaignTypes: this.options.campaignAppProfilePageState === 'ON' ? 'SPC_0,APPO_ON' : 'SPC_0,APPO_OFF',
        os: this.options.os
      }).finally(() => {
        this.campaignListLoading = false
      })
      this.campaignList = res.data
    },
    handleChangeCampaign(val) {
      const campaign = this.campaignList.find(item => item.id === val)
      if (campaign !== undefined) {
        console.log(campaign)
        this.campaignForm.budget = campaign.budget
        this.campaignForm.budgetMode = campaign.budgetMode
        this.campaignForm.campaignAppProfilePageState = campaign.campaignAppProfilePageState
        this.campaignForm.ios14Camppaign = campaign.campaignType === 'IOS14_CAMPAIGN'

      }
      this.getAdGroupList()
    },
    async handleChangeIos14Switch(val) {
      if (val) {
        const {data: res} = await getIos14Quota({
          appId: this.options.appId,
          platformId: this.campaignForm.platformId
        })
        if (res.data.campaignQuota.availableQuota < 1) {
          this.campaignForm.ios14Camppaign = false
          return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
        } else {
          this.levelQuota = res.data
        }
      }
    },
    // 查询所有广告组
    async getAdGroupList() {
      const {data: res} = await getAdGroupList({
        offerId: this.offerId,
        campaignId: this.campaignForm.campaignId
      })
      this.adGroupList = res.data
    },
    async getAdsByAdGroup() {
      const {data: res} = await getCopyAdgroupDetail({adGroupId: this.campaignForm.adGroupId})
      this.adLength = res.data.ttAdList.length
    },
    handleChangeCreateType(val) {
      this.campaignForm.adGroupId = ''
      this.campaignForm.campaignId = ''
      if (val === 2) {
        this.campaignForm.campaignAppProfilePageState = this.options.campaignAppProfilePageState
        this.campaignForm.ios14Camppaign = this.options.campaignType === 'IOS14_CAMPAIGN'
        this.$refs.adGroupForm.clearForm()
      }
    },
    handleChangeAdGroup(val) {
      const adGroup = this.adGroupList.find(item => item.id === val)
      if (adGroup !== undefined) {
        this.$refs.adGroupForm.initOption(adGroup)
      }
    },
    handleChangeCreateAdgroup(val) {
      this.campaignForm.adGroupId = ''
      if (val === 2) {
        this.$refs.adGroupForm.clearForm()
      }
    }
  }
}
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

.copy-campaign {
  ::v-deep .el-dialog {
    margin: 0 0 0 216px;
    width: calc(100vw - 220px);
    background: #fff0;
  }

  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }

  ::v-deep .el-dialog__header {
    padding: unset;
  }

  ::v-deep .el-dialog__body {
    padding: unset;
  }

  .root {
    height: calc(100vh - 115px);
    overflow: auto;
    display: flex;

    .campaign-card {
      height: 100%;
      width: 500px;
    }

    .edit-ad-group-box {
      display: flex;
      height: 100%;

      .edit-ad-group-box-new {
        width: 30%;
        overflow: auto;
      }

      .edit-ad-group-box-left {
        width: 40%;
        overflow: auto;
      }

      .edit-ad-group-box-right {
        width: 30%;
        overflow: auto;
        padding: 20px;
      }
    }
  }
}

.append-to-body {
  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }
}
</style>
